package com.hcb.app911;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.common.ActionEvent;
import com.hcb.constants.Constants;
import com.hcb.controller.CustomerController;
import com.hcb.dto.CustomerDTO;
import com.hcb.fragment.DatePickerFragment;
import com.hcb.model.utils.CustomerModel;
import com.hcb.webservice.InternetUtils;
import com.hcb.webservice.ServiceHandler;
import com.hcb.webservice.WebService;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class RegisterActivity extends FragmentActivity implements
		OnClickListener {

	Spinner spinerGender;
	String[] item;
	ArrayAdapter<String> AdapterGender;
	static final int DATE_PICKER_ID = 1111;
	CheckBox cbSigup;
	Button btnSigup;
	EditText edusername, edemail, edphonenumber, edAge;
	public DateAndTime requestedDateAndTime;
	public Context applicationContext;
	Button btnyes, btnno;

	Dialog dialog, existence, dialogerr;
	AnimationDrawable frameAnimation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_register);

		// Intent intent1 = new Intent(RegisterActivity.this,
		// MainActivity.class);
		// startActivity(intent1);
		// finish();

		btnSigup = (Button) findViewById(R.id.btnSigup);

		edusername = (EditText) findViewById(R.id.edusername);
		edemail = (EditText) findViewById(R.id.edemail);
		edphonenumber = (EditText) findViewById(R.id.edphonenumber);
		cbSigup = (CheckBox) findViewById(R.id.cbSigup);
		CustomerModel customer = CustomerModel.getInstance();
		int flagCustomer = customer.getFlagCustomer(this);
		if (flagCustomer == 0) {
			// Intent intent = new Intent(RegisterActivity.this,
			// MainActivity.class);
			// startActivity(intent);
			// finish();
			cbSigup.setOnClickListener(this);
			applicationContext = getApplicationContext();
			requestedDateAndTime = new DateAndTime(applicationContext);
			requestedDateAndTime.setToNow();

			edAge = (EditText) findViewById(R.id.edAge);
			// edAge.setInputType(InputType.TYPE_NULL);
			// edAge.requestFocus();
			// edAge.setOnClickListener(this);

			item = new String[2];
			item[0] = "male";
			item[1] = "female";
			AdapterGender = new ArrayAdapter<String>(this,
					android.R.layout.simple_spinner_item, item);
			AdapterGender
					.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
			spinerGender = (Spinner) findViewById(R.id.spinerGender);
			spinerGender.setAdapter(AdapterGender);
			spinerGender
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> parent,
								View view, int position, long id) {
							// TODO Auto-generated method stub

						}

						@Override
						public void onNothingSelected(AdapterView<?> parent) {
							// TODO Auto-generated method stub

						}
					});
		} else if (flagCustomer == 1) {
			Intent intent = new Intent(RegisterActivity.this,
					ValidationActivity.class);
			startActivity(intent);
			finish();
			// Intent intent = new Intent(RegisterActivity.this,
			// MainActivity.class);
			// startActivity(intent);
			// finish();

		} else if (flagCustomer == 2) {
			Intent intent = new Intent(RegisterActivity.this,
					MainActivity.class);
			startActivity(intent);
			finish();
		}

	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		String result;
		CustomerDTO customer;
		String customerid = "";
		final ServiceHandler sh = new ServiceHandler();
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		public VerySlowTask(CustomerDTO cus) {
			customer = cus;
			dialog = new Dialog(RegisterActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			// final ServiceHandler sh = new ServiceHandler();
			// final List<NameValuePair> nameValuePairs = new
			// ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.ADD_CUSTOMER));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));

			nameValuePairs.add(new BasicNameValuePair(Constants.NAME_CUSTOMER,
					customer.getName()));

			nameValuePairs.add(new BasicNameValuePair(
					Constants.EMAIL_ADDRESS_CUSTOMER, customer
							.getEmail_address()));
			nameValuePairs.add(new BasicNameValuePair(
					Constants.MOBILE_NUMBER_CUSTOMER, customer
							.getMobile_number()));
			nameValuePairs.add(new BasicNameValuePair(Constants.SEX_CUSTOMER,
					customer.getSex()));
			nameValuePairs.add(new BasicNameValuePair(Constants.AGE_CUSTOMER,
					customer.getAge()));

			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject object;
					object = new JSONObject(jsonStr);
					String value = object.getString("result");
					customerid = object.getString("data_body");
					customer.setCustomer_id(customerid);
					if (value.contains("success")) {

						ActionEvent e = new ActionEvent(RegisterActivity.this,
								Constants.INSERT_CUSTOMER, customer, null);
						CustomerController.getInstance().handleViewEvent(e);

						Intent intent = new Intent(RegisterActivity.this,
								ValidationActivity.class);
						// Bundle bundle = new Bundle();
						// bundle.putSerializable("customer", customer);
						// intent.putExtras(bundle);
						startActivity(intent);
						finish();
					} else {
						if (customerid
								.equalsIgnoreCase("This mobile number is already registered!")) {

						}
						//
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();
			if (customerid
					.equalsIgnoreCase("This mobile number is already registered!")) {

				existence = new Dialog(RegisterActivity.this,
						android.R.style.Theme_Translucent);
				existence.requestWindowFeature(Window.FEATURE_NO_TITLE);

				existence.setCancelable(true);
				existence.setContentView(R.layout.already_dialog);
				btnyes = (Button) existence.findViewById(R.id.btnyes);
				btnno = (Button) existence.findViewById(R.id.btnno);
				TextView txtNamedialog = (TextView) existence
						.findViewById(R.id.txtNamedialog);
				txtNamedialog
						.setText("this phone number was in existence, we will send code to this phone number, please verify.");

				btnyes.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						new VerySlowTaskExits(customer).execute();
						existence.dismiss();
					}
				});
				btnno.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						existence.dismiss();

					}
				});

				existence.show();
			} else {
				dialogerr = new Dialog(RegisterActivity.this,
						android.R.style.Theme_Translucent);
				dialogerr.requestWindowFeature(Window.FEATURE_NO_TITLE);

				dialogerr.setCancelable(true);
				dialogerr.setContentView(R.layout.dialog_err);
				TextView txtContent = (TextView) dialogerr
						.findViewById(R.id.txtContent);
				txtContent.setText(customerid);
				Button btnOke = (Button) dialogerr.findViewById(R.id.bntOk);

				btnOke.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						dialogerr.dismiss();
					}
				});

				dialogerr.show();
			}

		}

	}

	public class VerySlowTaskExits extends AsyncTask<Void, Void, Void> {
		String result;
		CustomerDTO customer;
		String customerid = "";
		final ServiceHandler sh = new ServiceHandler();
		final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

		public VerySlowTaskExits(CustomerDTO cus) {
			customer = cus;
			dialog = new Dialog(RegisterActivity.this, R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.SEND_VERIFICATIONCODE));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair(
					Constants.MOBILE_NUMBER_CUSTOMER, customer
							.getMobile_number()));

			String jsonStr1 = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);

			try {
				JSONObject object1;
				object1 = new JSONObject(jsonStr1);
				String value1 = object1.getString("result");
				if (value1.contains("success")) {
					Intent intent = new Intent(RegisterActivity.this,
							ValidationActivity.class);
					Bundle data = new Bundle();
					data.putInt("arler", 2);
					intent.putExtras(data);
					startActivity(intent);
					finish();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			dialog.dismiss();
			frameAnimation.stop();

		}

	}

	public final static boolean isValidEmail(CharSequence target) {
		return !TextUtils.isEmpty(target)
				&& android.util.Patterns.EMAIL_ADDRESS.matcher(target)
						.matches();
	}

	public boolean isValidInput(String email, String phone) {
		if (!isValidEmail(email)) {
			new AlertDialog.Builder(this)
					.setTitle("Error!")
					.setMessage("This email invalid, please input again.")
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// continue with delete
								}
							})
					/*
					 * .setNegativeButton(android.R.string.no, new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialog, int which) { // do
					 * nothing } })
					 */
					.setIcon(android.R.drawable.ic_dialog_alert).show();
			return false;
		}
		// get 3 number first.
		String numberstring = phone.substring(0, 3);
		if (!numberstring.equals("234")) {
			new AlertDialog.Builder(this)
					.setTitle("Error!")
					.setMessage(
							"This phone number invalid, please input phone begin 234.")
					.setPositiveButton(android.R.string.yes,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									// continue with delete
								}
							})
					/*
					 * .setNegativeButton(android.R.string.no, new
					 * DialogInterface.OnClickListener() { public void
					 * onClick(DialogInterface dialog, int which) { // do
					 * nothing } })
					 */
					.setIcon(android.R.drawable.ic_dialog_alert).show();
			return false;
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		// case R.id.edAge:
		// showDatePickerDialog(v);
		// break;
		case R.id.btnSigup:
			String name = edusername.getText().toString().trim();
			String email = edemail.getText().toString().trim();
			String phonenumber = edphonenumber.getText().toString().trim();
			String age = edAge.getText().toString().trim();
			String sex = spinerGender.getSelectedItem().toString().trim();
			CustomerDTO cus = new CustomerDTO();
			cus.setMobile_number(phonenumber);
			cus.setName(name);
			cus.setEmail_address(email);
			cus.setAge(age);
			cus.setSex(sex);
			if (cbSigup.isChecked() && isValidInput(email, phonenumber)) {
				if (!name.equalsIgnoreCase("") && !email.equalsIgnoreCase("")
						&& !phonenumber.equalsIgnoreCase("")
						&& !age.equalsIgnoreCase("")) {
					if (InternetUtils.getInstance()
							.isConnectingToInternet(this)) {
						new VerySlowTask(cus).execute();
					}

					// register regis = new register(cus,
					// RegisterActivity.this);
					//
					// new Thread(regis).start();

					// Fragment fragment = new ValidationFragment();
					// FragmentManager fragmentManager = this
					// .getSupportFragmentManager();
					// FragmentTransaction ft =
					// fragmentManager.beginTransaction();
					// ft.remove(fragment);
					// ft.replace(R.id.frame_container, fragment);
					// ft.commit();
				}

			} else {
				Toast.makeText(RegisterActivity.this,
						"No network please connect network", Toast.LENGTH_LONG)
						.show();
			}

			break;
		case R.id.cbSigup:
			if (cbSigup.isChecked()) {
				btnSigup.setBackgroundResource(R.drawable.signup);
				btnSigup.setOnClickListener(this);
			} else {
				btnSigup.setBackgroundResource(R.drawable.signupf);
			}
			break;
		default:
			break;
		}

	}

	public class PostData extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... params) {
			String server = "http://daluzzi.com/blue911/webservice/api.php,api_secret_key=["
					+ "3832_2hd3hdiwyu34eyeuidhd_948"
					+ "]&query=["
					+ "getCustomerList" + "]";

			new DefaultHttpClient();
			HttpPost httppost = new HttpPost(server);

			// httppost.setHeader("Accept", "application/json");
			httppost.setHeader("Accept", "application/x-www-form-urlencoded");
			// httppost.setHeader("Content-type", "application/json");
			httppost.setHeader("Content-Type",
					"application/x-www-form-urlencoded");

			return null;
		}

	}

	private class register implements Runnable {

		CustomerDTO customer;
		Context contextRunnable;

		public register(CustomerDTO cus, Context context) {
			customer = cus;
			contextRunnable = context;
		}

		@Override
		public void run() {
			String url = Constants.URL_SERVICE + "Register";
			url += "/api_secret_key/" + "3832_2hd3hdiwyu34eyeuidhd_948";
			url += "/query/" + "addCustomer";
			url += "/mobile_number/" + customer.getMobile_number();
			url += "/name/" + customer.getName();
			url += "/email_address/" + customer.getEmail_address();
			url += "/age/" + customer.getAge();
			url += "/sex/" + customer.getSex();

			String jsonResponse = WebService.getInstance().get(url);
			try {
				JSONObject object;
				object = new JSONObject(jsonResponse);
				String value = object.getString("result");
				String customerid = object.getString("data_body");
				customer.setCustomer_id(customerid);
				if (value.contains("success")) {

					ActionEvent e = new ActionEvent(RegisterActivity.this,
							Constants.INSERT_CUSTOMER, customer, null);
					CustomerController.getInstance().handleViewEvent(e);

					Intent intent = new Intent(contextRunnable,
							ValidationActivity.class);
					// Bundle bundle = new Bundle();
					// bundle.putSerializable("customer", customer);
					// intent.putExtras(bundle);
					startActivity(intent);
					finish();
				} else {
					if (customerid
							.equalsIgnoreCase("This mobile number is already registered!")) {
						String url1 = Constants.URL_SERVICE
								+ "sendVerificationCode";
						url1 += "/api_secret_key/"
								+ "3832_2hd3hdiwyu34eyeuidhd_948";
						url1 += "/query/" + "sendVerificationCode";
						url1 += "/mobile_number/" + customer.getMobile_number();
						String jsonResponse1 = WebService.getInstance().get(
								url1);
						try {
							JSONObject object1;
							object1 = new JSONObject(jsonResponse1);
							String value1 = object1.getString("result");
							if (value1.contains("success")) {
								Intent intent = new Intent(contextRunnable,
										ValidationActivity.class);
								Bundle data = new Bundle();
								data.putInt("arler", 2);
								intent.putExtras(data);
								startActivity(intent);
								finish();
							}

						} catch (Exception e) {
							e.printStackTrace();
						}
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
				return;
			}

		}

	}

	public void updateDateDisplay(String dateString) {
		edAge.setText(dateString);
	}

	public void showDatePickerDialog(View v) {
		DialogFragment newFragment = new DatePickerFragment();
		newFragment.show(getSupportFragmentManager(), "datePicker");
	}
}
